//
//  AppDelegate.m
//  ZITHER
//
//  Created by weixin on 2018/7/23.
//  Copyright © 2018年 weixn. All rights reserved.
//

#import "AppDelegate.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "MainTabBarController.h"
#import <UMCommon/UMCommon.h>
#import <UMShare/UMShare.h>
#import <UMPush/UMessage.h>
#import <UMAnalytics/MobClick.h>
#import <UserNotifications/UserNotifications.h>
#import "STViewController.h"
#import "MainFirst_Magazine_VC_WX.h"
#import "Ugc_Detail_VC_WX.h"


@interface AppDelegate ()<UIApplicationDelegate,UNUserNotificationCenterDelegate>


@end


@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:kScreenBOUNDS];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = [[UIViewController alloc]init];;
    [self.window makeKeyAndVisible];    if (URL_SERVICE !=4) {
        Main_Token_Model_MANAGER.RootUrl = RootUrl;
    }


    if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"0"]) {
        [self func1:launchOptions];

    }else if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"1"]){
        [self func1:launchOptions];
        
    }else{
        
        self.window = [[UIWindow alloc] initWithFrame:kScreenBOUNDS];
        self.window.backgroundColor = [UIColor whiteColor];
        self.window.rootViewController = [[UIViewController alloc]init];;
        [self.window makeKeyAndVisible];
        
        if (![Main_Token_Model_MANAGER.RootUrl isEqualToString:RootUrl]) {
            if (URL_SERVICE ==4) {
                Main_Token_Model_MANAGER.RootUrl = RootUrl;
            }
            [[AFHTTPSessionManager shareManager] jwxSecurity];
        }
        [Main_Token_Model_MANAGER saveUserInfoSelf];
        [[AccountService loadUserCreateppp:nil]subscribeNext:^(ResponseData * x) {
            if (x.success) {
                [Main_Token_Model_MANAGER func2:x.responseRawData[@"data"]];
            }else{
                Main_Token_Model_MANAGER.isToken = @"1";
            }
            Main_Token_Model_MANAGER.backgroundColor = [UIColor colorWithHex:@"#FFC638"];
            Main_Token_Model_MANAGER.navTitleColor = [UIColor whiteColor];
            Main_Token_Model_MANAGER.postfixIcon = @"WX";
            [self func1:launchOptions];
            [Main_Token_Model_MANAGER saveUserInfoSelf];
            
        }];
        
    }


    return YES;

}

-(void)func1:(NSDictionary *)dic{

    [self setkeyboardManager];
    
    [self setMainTabBarController];
    
    [self setUM];
    /** 推送 */
    
    [self configUMessage:dic];
    
}




-(void)setMainTabBarController{

    MainTabBarController * tbVC = [[MainTabBarController alloc] init];
    [tbVC def:0];
    self.window.rootViewController = tbVC;
    [self.window makeKeyAndVisible];

//        [self.launchAD setAD];
}


-(void)setkeyboardManager{
    
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager]; // 获取类库的单例变量
    
    keyboardManager.enable = YES; // 控制整个功能是否启用
    
    keyboardManager.shouldResignOnTouchOutside = YES; // 控制点击背景是否收起键盘
    
    keyboardManager.shouldToolbarUsesTextFieldTintColor = YES; // 控制键盘上的工具条文字颜色是否用户自定义
    
    keyboardManager.toolbarManageBehaviour = IQAutoToolbarBySubviews; // 有多个输入框时，可以通过点击Toolbar 上的“前一个”“后一个”按钮来实现移动到不同的输入框
    
    keyboardManager.enableAutoToolbar = YES; // 控制是否显示键盘上的工具条
    
    keyboardManager.shouldShowToolbarPlaceholder = YES; // 是否显示占位文字
    
    keyboardManager.placeholderFont = [UIFont boldSystemFontOfSize:17]; // 设置占位文字的字体
    
    keyboardManager.keyboardDistanceFromTextField = 10.0f; // 输入框距离键盘的距离
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO; //  DONE
    
    //    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;

}


// 支持所有iOS系统
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
//    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
//    if (!result) {
//        // 其他如支付等SDK的回调
//    }
//    return result;
//}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如等SDK的回调
    }
    return result;
}

-(void)setUM{
    NSString *str = Main_Token_Model_MANAGER.umkey;
    
    //代码写在这个里面
    [UMConfigure initWithAppkey:str channel:@"App Store"];
    //代码写在这个里面
    [UMConfigure setLogEnabled:NO];
    // U-Share 平台设置
    [self configUSharePlatforms];
    [self confitUShareSettings];
 
}

- (void)confitUShareSettings
{
    
}

- (void)configUSharePlatforms
{
    NSLog(@"Main_Token_Model_MANAGER %@",Main_Token_Model_MANAGER);
//    NSString *str = Main_Token_Model_MANAGER.wxKey;
     [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:    Main_Token_Model_MANAGER.wxKey appSecret:Main_Token_Model_MANAGER.wxfxS redirectURL:@"http://mobile.umeng.com/social"];
    
    
//    [[serviceDefualt loadWechat:nil]subscribeNext:^(ResponseData * x) {
//        if (x.success) {
            /* 设置微信的appKey和appSecret */
//            [[UMSocialManager defaultManager]openLog:YES];;

//            [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:x.responseRawData[@"data"][@"appId"] appSecret:x.responseRawData[@"data"][@"appSecret"] redirectURL:@"http://mobile.umeng.com/social"];
//        }
//    }];

    /*
     * 移除相应平台的分享，如微信收藏
     */
    //[[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:Main_Token_Model_MANAGER.txKey/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    
    NSLog(@"%@ ======= %@",Main_Token_Model_MANAGER.wbKey,Main_Token_Model_MANAGER.wbfxS);
    /* 设置新浪的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:Main_Token_Model_MANAGER.wbKey appSecret:Main_Token_Model_MANAGER.wbfxS redirectURL:@"https://sns.whalecloud.com/sina2/callback"];

}


/** 友盟推送 */
-(void)configUMessage:(NSDictionary*)launchOptions{
    [UMConfigure initWithAppkey:Main_Token_Model_MANAGER.pushKey channel:@"App Store"];
    // Push组件基本功能配置
    UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
    //type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标
    entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionSound|UMessageAuthorizationOptionAlert;
    if (@available(iOS 10.0, *)) {
        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    } else {
        // Fallback on earlier versions
    }
    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity     completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
        }else{
        }
    }];

    [UMessage setBadgeClear:YES];
    
    [UMessage openDebugMode:YES];
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //关闭友盟自带的弹出框
    [UMessage setAutoAlert:NO];
    [UMessage didReceiveRemoteNotification:userInfo];

    //    self.userInfo = userInfo;
    //    //定制自定的的弹出框
    //    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
    //    {
    //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"标题"
    //                                                            message:@"Test On ApplicationStateActive"
    //                                                           delegate:self
    //                                                  cancelButtonTitle:@"确定"
    //                                                  otherButtonTitles:nil];
    //
    //        [alertView show];
    //
    //    }

}


/** schme访问App */
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    [self setupAppWithURL:url];
    return YES;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    [self setupAppWithURL:url];
    return YES;
}

- (void)setupAppWithURL:(NSURL *)url
{
    
    // 3.每次跳转前必须是在跟控制器(细节)
    //    [rootNav popToRootViewControllerAnimated:NO];
    
    NSString *urlStr = url.absoluteString;


    if ([url.absoluteString containsString:@"sku"]) {//与DemoA约定好的字符
        urlStr = [urlStr componentsSeparatedByString:@"sku?goodId="][1];
        STViewController *vc = [[STViewController alloc]init];
        vc.type = STControllerTypeHiddenNavBar;
        vc.goodId = urlStr;
        [[self currentNC] pushViewController:vc animated:YES];
    }else if ([url.absoluteString containsString:@"pgc"]) {
        urlStr = [urlStr componentsSeparatedByString:@"pgcdetail?pgcId="][1];
        MainFirst_Magazine_VC_WX *vc = [[MainFirst_Magazine_VC_WX alloc]init];
        vc.pgcId = urlStr;
        [[self currentNC] pushViewController:vc animated:YES];
    }else if ([url.absoluteString containsString:@"ugc"]) {
        urlStr = [urlStr componentsSeparatedByString:@"ugcdetail?ugcId="][1];
        Ugc_Detail_VC_WX *vc = [[Ugc_Detail_VC_WX alloc]init];
        vc.ugcId = urlStr;
        [[self currentNC] pushViewController:vc animated:YES];
    }else {
        

    }
}

-(void)getUrlType{
    
}
-(UINavigationController *)currentNC
{
    if (![[UIApplication sharedApplication].windows.lastObject isKindOfClass:[UIWindow class]]) {
        NSAssert(0, @"未获取到导航控制器");
        return nil;
    }
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    return [self getCurrentNCFrom:rootViewController];
}

//递归
- (UINavigationController *)getCurrentNCFrom:(UIViewController *)vc
{
    if ([vc isKindOfClass:[UITabBarController class]]) {
        UINavigationController *nc = ((UITabBarController *)vc).selectedViewController;
        return [self getCurrentNCFrom:nc];
    }
    else if ([vc isKindOfClass:[UINavigationController class]]) {
        if (((UINavigationController *)vc).presentedViewController) {
            return [self getCurrentNCFrom:((UINavigationController *)vc).presentedViewController];
        }
        return [self getCurrentNCFrom:((UINavigationController *)vc).topViewController];
    }
    else if ([vc isKindOfClass:[UIViewController class]]) {
        if (vc.presentedViewController) {
            return [self getCurrentNCFrom:vc.presentedViewController];
        }
        else {
            return vc.navigationController;
        }
    }
    else {
        NSAssert(0, @"未获取到导航控制器");
        return nil;
    }
}



/* MARK: =================  推送相关代码 =================*/


 -(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
     
     NSLog(@"");
     NSLog(@"%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                   stringByReplacingOccurrencesOfString: @">" withString: @""]
                  stringByReplacingOccurrencesOfString: @" " withString: @""]);
     [UMessage registerDeviceToken:deviceToken];
     NSLog(@"");

 }


//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            
            //应用处于前台时的远程推送接受
            //关闭U-Push自带的弹出框
            [UMessage setAutoAlert:NO];
            //必须加这句代码
            [UMessage didReceiveRemoteNotification:userInfo];
            
        }else{
            //应用处于前台时的本地推送接受
        }
    } else {
        // Fallback on earlier versions
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    }
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        //应用处于后台时的本地推送接受
    }
}

 
//iOS10以下使用这两个方法接收通知，
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [UMessage setAutoAlert:NO];
    if([[[UIDevice currentDevice] systemVersion]intValue] < 10){
        [UMessage didReceiveRemoteNotification:userInfo];
        
        //    self.userInfo = userInfo;
        //    //定制自定的的弹出框
        //    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
        //    {
        //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"标题"
        //                                                            message:@"Test On ApplicationStateActive"
        //                                                           delegate:self
        //                                                  cancelButtonTitle:@"确定"
        //                                                  otherButtonTitles:nil];
        //
        //        [alertView show];
        //
        //    }
        completionHandler(UIBackgroundFetchResultNewData);
    }
}




@end
